package ai.mspbots.test.service;

import ai.mspbots.test.dto.AzureAIConfig;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@Slf4j
@Service
@RequiredArgsConstructor
public class AzureAIVerificationService {

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    /**
     * 验证 Azure AI 配置有效性
     */
    public boolean verifyAzureAIKey(AzureAIConfig config) {
        return verifyAzureAIKey(
            config.getApiKey(),
            config.getAzureEndpoint(),
            config.getApiVersion(),
            config.getDeploymentName()
        );
    }

    /**
     * 验证 Azure AI Key 有效性
     */
    public boolean verifyAzureAIKey(String apiKey, String azureEndpoint, 
                                   String apiVersion, String deploymentName) {
        try {
            // 构建完整的API URL
            String apiUrl = buildVerificationUrl(azureEndpoint, deploymentName, apiVersion);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("api-key", apiKey);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            // 构建请求体（简单的聊天请求）
            String requestBody = """
            {
                "messages": [
                    {
                        "role": "user",
                        "content": "Hello"
                    }
                ],
                "max_tokens": 5,
                "temperature": 0.1
            }
            """;

            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            // 发送验证请求
            ResponseEntity<String> response = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                entity,
                String.class
            );

            // 检查响应状态
            if (response.getStatusCode() == HttpStatus.OK) {
                log.info("Azure AI Key 验证成功");
                return true;
            } else {
                log.warn("Azure AI Key 验证失败，状态码: {}", response.getStatusCode());
                return false;
            }

        } catch (Exception e) {
            log.error("Azure AI Key 验证异常: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 构建验证URL
     */
    private String buildVerificationUrl(String azureEndpoint, String deploymentName, String apiVersion) {
        // 确保端点以斜杠结尾
        String endpoint = azureEndpoint.endsWith("/") ? azureEndpoint : azureEndpoint + "/";
        
        return String.format("%sopenai/deployments/%s/chat/completions?api-version=%s",
            endpoint, deploymentName, apiVersion);
    }

    /**
     * 更详细的验证，返回验证结果信息
     */
    public VerificationResult verifyAzureAIKeyWithDetails(AzureAIConfig config) {
        try {
            String apiUrl = buildVerificationUrl(config.getAzureEndpoint(), 
                                               config.getDeploymentName(), 
                                               config.getApiVersion());

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("api-key", config.getApiKey());
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            String requestBody = """
            {
                "messages": [
                    {
                        "role": "user",
                        "content": "Hello"
                    }
                ],
                "max_tokens": 5,
                "temperature": 0.1
            }
            """;

            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            ResponseEntity<String> response = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                entity,
                String.class
            );

            if (response.getStatusCode() == HttpStatus.OK) {
                JsonNode responseJson = objectMapper.readTree(response.getBody());
                return VerificationResult.success("验证成功", responseJson);
            } else {
                return VerificationResult.failure("验证失败，状态码: " + response.getStatusCode());
            }

        } catch (org.springframework.web.client.HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                return VerificationResult.failure("API Key 无效或未授权");
            } else if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                return VerificationResult.failure("部署名称不存在或端点错误");
            } else if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
                return VerificationResult.failure("请求参数错误: " + e.getResponseBodyAsString());
            } else {
                return VerificationResult.failure("HTTP错误: " + e.getStatusCode());
            }
        } catch (Exception e) {
            return VerificationResult.failure("验证异常: " + e.getMessage());
        }
    }

    /**
     * 列出可用的模型（另一种验证方式）
     */
    public boolean verifyByListingModels(AzureAIConfig config) {
        try {
            String apiUrl = String.format("%sopenai/models?api-version=%s",
                config.getAzureEndpoint().endsWith("/") ? config.getAzureEndpoint() : config.getAzureEndpoint() + "/",
                config.getApiVersion());

            HttpHeaders headers = new HttpHeaders();
            headers.set("api-key", config.getApiKey());

            HttpEntity<String> entity = new HttpEntity<>(headers);

            ResponseEntity<String> response = restTemplate.exchange(
                apiUrl,
                HttpMethod.GET,
                entity,
                String.class
            );

            return response.getStatusCode() == HttpStatus.OK;

        } catch (Exception e) {
            log.error("列出模型验证失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 验证结果类
     */
    @Data
    public static class VerificationResult {
        private boolean success;
        private String message;
        private JsonNode details;

        public static VerificationResult success(String message, JsonNode details) {
            VerificationResult result = new VerificationResult();
            result.success = true;
            result.message = message;
            result.details = details;
            return result;
        }

        public static VerificationResult failure(String message) {
            VerificationResult result = new VerificationResult();
            result.success = false;
            result.message = message;
            return result;
        }
    }
}